package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.IntegralDao;
import dao.impl.IntegralDaoImpl;
import domian.Integral;
import domian.User;
import redis.clients.jedis.Jedis;
import utils.Redis;
import utils.ToolSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/integralServlet/*")
public class IntegralServlet extends BaseServlet{
    //积分变动数据访问层
    IntegralDao ido = new IntegralDaoImpl();

    public void FindIntegralAll(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Jedis jedis = new Jedis();
        //获取用户客户端标识
        String redisKey = Redis.getRedisKey(req);
        //获得登录用户对象
        String json = jedis.get(redisKey);

        ObjectMapper om = new ObjectMapper();

        User user = null;
        if (json != null && !json.isEmpty()){
            user = om.readValue(json,User.class);

            //获得登录用户id
            Integer uid = user.getUid();

            List<Integral> inquireAll = ido.findInquireAll(uid);

            int topup = 0;  //充值积分
            int register = 0;   //注册赠送
            int upload = 0;     //资源上传
            int comment = 0;    //评论资源
            int download = 0;   //下载资源
            for (Integral tl : inquireAll) {
                String ft = tl.getCause();  //变动原因
                int it = tl.getIntegral();
                if (ft.equals("用户注册赠送积分")){    //注册时的增加积分
                    register += it;
                }else if ("开通会员赠送积分".equals(ft)){
                    topup += it;
                }else if ("资源被下载赠送积分".equals(ft)){
                    download += it;
                }else if ("资源被评论赠送积分".equals(ft)){
                    comment += it;
                }else if ("上传资源赠送积分".equals(ft)){
                    upload += it;
                }
            }

            Map<String,Integer> map = new HashMap<>();
            map.put("topup",topup);
            map.put("register",register);
            map.put("upload",upload);
            map.put("comment",comment);
            map.put("download",download);

            ToolSet.printWriter(resp,map);
        }


    }
}
